package br.com.equus.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.arquitetura.DAO.UniversalDAO;
import br.com.equus.entidade.Animal;
import br.com.equus.entidade.ControleReceptora;
import br.com.equus.service.ReceptoraService;

@Service(value = "receptoraService")
@Transactional(readOnly = true, rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
public class ReceptoraServiceImpl implements ReceptoraService {

	@Autowired(required = true)
	@Qualifier(value = "universalDAO")
	protected UniversalDAO dao;

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void save(ControleReceptora animalEfetivado, Animal animal) throws Exception {
		dao.save(animalEfetivado);
		dao.merge(animal);
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void deleteReceptora(ControleReceptora model, Animal animal) throws Exception {

		if (model.getFlgEmbriaoEfetivado() != null && model.getFlgEmbriaoEfetivado()) {
			if (animal.getQtdParto() == null || animal.getQtdParto() == 0) {
				animal.setQtdParto(0);
			} else {
				animal.setQtdParto(animal.getQtdParto() - 1);
			}
		} else if (model.getFlgEmbriaoEfetivado() != null && !model.getFlgEmbriaoEfetivado()) {
			if (animal.getQtdAborto() == null || animal.getQtdAborto() == 0) {
				animal.setQtdAborto(0);
			} else {
				animal.setQtdAborto(animal.getQtdAborto() - 1);
			}
		}

		dao.remove(ControleReceptora.class, model.getId());

		dao.merge(animal);

	}

}
